import {
  Request,
  Response,
  Router,
} from 'express';

import { IUser } from '@shared/types/user';

import { User } from '../models/user.model';

export const userRouter = Router();

// 获取用户列表（支持分页和搜索）
userRouter.get("/list", async (req: Request, res: Response) => {
  try {
    const {
      page = 1,
      pageSize = 20,
      username,
      phone,
      role,
      status
    } = req.query;

    const filter: any = { is_deleted: false }; // 默认只查询未删除的用户
    if (username) filter.username = { $regex: username, $options: 'i' };
    if (phone) filter.phone = { $regex: phone, $options: 'i' };
    if (role) filter.role = role;
    if (status) filter.status = status;

    const limit = parseInt(pageSize as string);
    const skip = (parseInt(page as string) - 1) * limit;

    const users = await User.find(filter)
      .select('-password') // 不返回密码
      .skip(skip)
      .limit(limit)
      .sort({ create_time: -1 });

    const total = await User.countDocuments(filter);

    res.json({
      code: 200,
      message: "success",
      data: {
        data: users,
        total_records: total,
        page: parseInt(page as string),
        limit,
        total_page: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({ 
      code: 500,
      message: "获取用户列表失败",
      data: null
    });
  }
});

// 获取用户详情
userRouter.get("/detail", async (req: Request, res: Response) => {
  try {
    const { id } = req.query;
    if (!id) {
      return res.status(400).json({
        code: 400,
        message: "用户ID不能为空",
        data: null
      });
    }

    const user = await User.findOne({ _id: id, is_deleted: false }).select('-password');
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
        data: null
      });
    }

    res.json({
      code: 200,
      message: "success",
      data: user
    });
  } catch (error) {
    console.error('获取用户详情失败:', error);
    res.status(500).json({ 
      code: 500,
      message: "获取用户详情失败",
      data: null
    });
  }
});

// 创建新用户
userRouter.post("/create", async (req: Request, res: Response) => {
  try {
    const userData: IUser = req.body;
    
    // 验证必填字段
    if (!userData.username || !userData.phone || !userData.password) {
      return res.status(400).json({
        code: 400,
        message: "用户名、手机号和密码不能为空",
        data: null
      });
    }

    // 检查手机号是否已存在
    const existingUser = await User.findOne({ phone: userData.phone });
    if (existingUser) {
      return res.status(400).json({
        code: 400,
        message: "手机号已存在",
        data: null
      });
    }

    const user = new User(userData);
    const savedUser = await user.save();
    
    // 返回时不包含密码
    const userResponse = savedUser.toObject();
    const { password, ...userWithoutPassword } = userResponse;

    res.status(201).json({
      code: 201,
      message: "用户创建成功",
      data: userWithoutPassword
    });
  } catch (error) {
    console.error('创建用户失败:', error);
    res.status(500).json({ 
      code: 500,
      message: "创建用户失败",
      data: null
    });
  }
});

// 更新用户信息
userRouter.post("/update", async (req: Request, res: Response) => {
  try {
    const { id, ...updateData } = req.body;
    
    if (!id) {
      return res.status(400).json({
        code: 400,
        message: "用户ID不能为空",
        data: null
      });
    }

    // 如果更新手机号，检查是否已存在
    if (updateData.phone) {
      const existingUser = await User.findOne({ 
        phone: updateData.phone, 
        _id: { $ne: id } 
      });
      if (existingUser) {
        return res.status(400).json({
          code: 400,
          message: "手机号已存在",
          data: null
        });
      }
    }

    // 不允许直接更新密码（应该有专门的修改密码接口）
    delete updateData.password;
    
    const updatedUser = await User.findByIdAndUpdate(
      id, 
      updateData, 
      { new: true }
    ).select('-password');

    if (!updatedUser) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
        data: null
      });
    }

    res.json({
      code: 200,
      message: "用户信息更新成功",
      data: updatedUser
    });
  } catch (error) {
    console.error('更新用户失败:', error);
    res.status(500).json({ 
      code: 500,
      message: "更新用户失败",
      data: null
    });
  }
});

// 删除用户
// 批量软删除用户
userRouter.post("/delete", async (req: Request, res: Response) => {
  try {
    const { id, ids } = req.body;
    const currentUser = req.user as any;
    
    if (ids && Array.isArray(ids)) {
      // 批量删除
      // 检查是否包含管理员账户或当前用户
      const usersToDelete = await User.find({ 
        _id: { $in: ids }, 
        is_deleted: false 
      });
      
      const adminUsers = usersToDelete.filter(user => user.role === 'admin');
      const currentUserInList = usersToDelete.find(user => user._id.toString() === currentUser.user_id);
      
      if (adminUsers.length > 0) {
        return res.status(403).json({
          code: 403,
          message: "不能删除管理员账户",
          data: null
        });
      }
      
      if (currentUserInList) {
        return res.status(403).json({
          code: 403,
          message: "不能删除自己的账户",
          data: null
        });
      }
      
      const result = await User.updateMany(
        { _id: { $in: ids }, is_deleted: false },
        { 
          is_deleted: true, 
          deleted_at: new Date(),
          status: 'disabled'
        }
      );
      
      res.json({
        code: 200,
        message: `成功删除 ${result.modifiedCount} 个用户`,
        data: { deletedCount: result.modifiedCount }
      });
    } else if (id) {
      // 单个删除
      const userToDelete = await User.findOne({ _id: id, is_deleted: false });
      if (!userToDelete) {
        return res.status(404).json({
          code: 404,
          message: "用户不存在或已被删除",
          data: null
        });
      }
      
      if (userToDelete.role === 'admin') {
        return res.status(403).json({
          code: 403,
          message: "不能删除管理员账户",
          data: null
        });
      }
      
      if (userToDelete._id.toString() === currentUser.user_id) {
        return res.status(403).json({
          code: 403,
          message: "不能删除自己的账户",
          data: null
        });
      }
      
      await User.findByIdAndUpdate(id, {
        is_deleted: true,
        deleted_at: new Date(),
        status: 'disabled'
      });
      
      res.json({
        code: 200,
        message: "用户删除成功",
        data: null
      });
    } else {
      res.status(400).json({
        code: 400,
        message: "请提供要删除的用户ID",
        data: null
      });
    }
  } catch (error) {
    console.error('删除用户失败:', error);
    res.status(500).json({ 
      code: 500,
      message: "删除用户失败",
      data: null
    });
  }
});

// 重置用户密码
userRouter.post("/reset-password", async (req: Request, res: Response) => {
  try {
    const { id, newPassword } = req.body;
    
    if (!id || !newPassword) {
      return res.status(400).json({
        code: 400,
        message: "用户ID和新密码不能为空",
        data: null
      });
    }

    const updatedUser = await User.findByIdAndUpdate(
      id,
      { password: newPassword },
      { new: true }
    ).select('-password');

    if (!updatedUser) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在", 
        data: null
      });
    }

    res.json({
      code: 200,
      message: "密码重置成功",
      data: null
    });
  } catch (error) {
    console.error('重置密码失败:', error);
    res.status(500).json({ 
      code: 500,
      message: "重置密码失败",
      data: null
    });
  }
});

// 软删除用户
userRouter.delete("/:id", async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const currentUser = req.user as any; // 当前登录用户信息

    // 检查要删除的用户是否存在且未被删除
    const userToDelete = await User.findOne({ _id: id, is_deleted: false });
    if (!userToDelete) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在或已被删除",
        data: null
      });
    }

    // 检查是否试图删除管理员账户
    if (userToDelete.role === 'admin') {
      return res.status(403).json({
        code: 403,
        message: "不能删除管理员账户",
        data: null
      });
    }

    // 检查是否试图删除自己
    if (userToDelete._id.toString() === currentUser.user_id) {
      return res.status(403).json({
        code: 403,
        message: "不能删除自己的账户",
        data: null
      });
    }

    // 执行软删除
    await User.findByIdAndUpdate(id, {
      is_deleted: true,
      deleted_at: new Date(),
      status: 'disabled' // 同时禁用账户
    });

    res.json({
      code: 200,
      message: "用户删除成功",
      data: null
    });
  } catch (error) {
    console.error('删除用户失败:', error);
    res.status(500).json({
      code: 500,
      message: "删除用户失败",
      data: null
    });
  }
});

// 恢复已删除的用户（可选功能）
userRouter.post("/:id/restore", async (req: Request, res: Response) => {
  try {
    const { id } = req.params;

    // 检查用户是否存在且已被删除
    const user = await User.findOne({ _id: id, is_deleted: true });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在或未被删除",
        data: null
      });
    }

    // 恢复用户
    await User.findByIdAndUpdate(id, {
      is_deleted: false,
      deleted_at: null,
      status: 'active'
    });

    res.json({
      code: 200,
      message: "用户恢复成功",
      data: null
    });
  } catch (error) {
    console.error('恢复用户失败:', error);
    res.status(500).json({
      code: 500,
      message: "恢复用户失败",
      data: null
    });
  }
});

// 获取已删除用户列表（管理员功能）
userRouter.get("/deleted/list", async (req: Request, res: Response) => {
  try {
    const {
      page = 1,
      pageSize = 20,
      username,
      phone
    } = req.query;

    const filter: any = { is_deleted: true }; // 只查询已删除的用户
    if (username) filter.username = { $regex: username, $options: 'i' };
    if (phone) filter.phone = { $regex: phone, $options: 'i' };

    const limit = parseInt(pageSize as string);
    const skip = (parseInt(page as string) - 1) * limit;

    const users = await User.find(filter)
      .select('-password')
      .skip(skip)
      .limit(limit)
      .sort({ deleted_at: -1 });

    const total = await User.countDocuments(filter);

    res.json({
      code: 200,
      message: "success",
      data: {
        data: users,
        total_records: total,
        page: parseInt(page as string),
        limit,
        total_page: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('获取已删除用户列表失败:', error);
    res.status(500).json({
      code: 500,
      message: "获取已删除用户列表失败",
      data: null
    });
  }
});
